package com.xiaowu.web.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import com.xiaowu.web.dao.RoleMapper;
import com.xiaowu.web.dao.RoleResourceMapper;
import com.xiaowu.web.model.Resource;
import com.xiaowu.web.model.Role;
import com.xiaowu.web.model.RoleResource;
import com.xiaowu.web.service.IRoleService;


@Service("roleService")
public class RoleServiceImpl extends BaseService<Role> implements IRoleService {

	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private RoleResourceMapper roleResourceMapper;

	@Override
	public List<Role> selectAllByMap(Map<String, Object> map) {
		Example example = new Example(Role.class);
		Example.Criteria criteria = example.createCriteria();
		//状态（0启用，1禁用）
		if(StringUtils.isNotBlank(MapUtils.getString(map, "status"))){
			criteria.andEqualTo("status",MapUtils.getString(map, "status"));
		}
		//名称
		if (StringUtil.isNotEmpty(MapUtils.getString(map, "name"))) {
            criteria.andLike("name", "%" + MapUtils.getString(map, "name") + "%");
        }
		//描述
		if (StringUtil.isNotEmpty(MapUtils.getString(map, "description"))) {
            criteria.andLike("description", "%" + MapUtils.getString(map, "description") + "%");
        }
		return roleMapper.selectByExample(example);
	}
	
	@Override
	public int updateRoleResource(Integer id, String resource) {
		Example example = new Example(RoleResource.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("roleId",id);
		roleResourceMapper.deleteByExample(example);

		if(StringUtils.isNotBlank(resource)){
			RoleResource roleResource;
			String[] resourceSplit = resource.split(",");
			for (int i = 0; i < resourceSplit.length; i++) {
				roleResource = new RoleResource();
				roleResource.setRoleId(id);
				roleResource.setResourceId(Integer.parseInt(resourceSplit[i]));
				roleResourceMapper.insert(roleResource);
			}
		}
		
		return 0;
	}
	
	@Override
	public int addRole(Role role) {
		return roleMapper.insertSelective(role);
	}
	
	@Override
	public int updateRole(Role role) {
		Example example = new Example(Resource.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("id",role.getId());
		return roleMapper.updateByExample(role, example);
	}
	
	@Override
	public int deleteRole(Role role) {
		return roleMapper.delete(role);
	}
	
	@Override
	public Role selectById(Role role) {
		return roleMapper.selectOne(role);
	}

}
